<template>
  <!-- 订单发货组件 -->
  <div v-loading="loading" element-loading-text="加载中">

    <div class="flex">
      <div style="flex: 6;">
        <el-row class="pad-b-10">
          <el-col :span="4" align="right"><label>收货人：</label></el-col>
          <el-col :span="16"><span>{{ apartOrderObj.projectOrder.customerNickname }}</span></el-col>
          <el-col :span="4" align="right">
            <template v-if="apartOrderObj.projectOrder.encryptReceiveFlag == 1">
              <el-tooltip class="item" effect="dark" content="点击查看收货信息" placement="top-start">
                <img :src="isLock ? lockIcon : unlockIcon" class="width-24 cursor-p" style="position: absolute; right: 15px; top: 5px; z-index: 99;" @click="doDecrypt(0)">
              </el-tooltip>
            </template>
          </el-col>
        </el-row>
        <el-row class="pad-b-10">
          <el-col :span="4" align="right"><label>收货人电话：</label></el-col>
          <el-col :span="16"><span>{{ apartOrderObj.projectOrder.customerPhone }}</span></el-col>
        </el-row>
        <el-row>
          <el-col :span="4" align="right"><label>收货地址：</label></el-col>
          <el-col :span="16"><span>{{ apartOrderObj.projectOrder.customerFullAddress }}</span></el-col>
        </el-row>

        <el-divider></el-divider>

        <div class="pad-l-10">
          <p><strong>订单商品明细</strong></p>
          <el-table :data="orderGoodsList" v-loading="listLoading" element-loading-text="加载中" height="450">
            <el-table-column width="220px" label="商品信息">
              <template slot-scope="scope">
                <div class="flex v-align-c">
                  <label><img :src="scope.row.goodsImageUrl" class="t-goods-pic"></label>
                  <div class="font-14 pad-l-10">
                    <div class="line-2">
                      <span title="赠品" v-if="scope.row.giftFlag == 1"><svg-icon icon-class="gift" class="font-20"/></span>
                      <span>{{ scope.row.goodsTitle }}</span>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column width="160px" label="规格描述" align="left">
              <template slot-scope="scope">
                <div class="line-2">{{ scope.row.skuDetail ? scope.row.skuDetail : '--'}}</div>
              </template>
            </el-table-column>
            <el-table-column width="140px" label="总数量/可发货数量" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.goodsNum }}</span>
                <span>/</span>
                <span>{{ scope.row.canSplitNum }}</span>
              </template>
            </el-table-column>
            <el-table-column width="140px" label="发货数量" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.splitNum"
                  class="pad-10"
                  @keyup.native="scope.row.splitNum = checkInputNumWithPoint(scope.row.splitNum, 0)"
                  :disabled="!scope.row.editNumFlag">
                </el-input>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 底部按钮 -->
        <div class="mar-t-20 mar-b-10" style="text-align: right;">
          <el-button @click="initGoodsList">重置发货数量</el-button>
          <el-button type="primary" :disabled="generateBtnDisable" @click="doGenerateSend">生成发货单</el-button>
          <el-button @click="doClose">关闭</el-button>
        </div>
      </div>

      <el-divider direction="vertical"></el-divider>

      <div style="flex: 6;">
        <div class="table-container">
          <p><strong>发货单列表</strong></p>
          <el-table :data="sendList" v-loading="sendListLoading" element-loading-text="加载中" height="570">
            <el-table-column width="230px" label="发货单号" fixed="left">
              <template slot-scope="scope">
                <div>{{ scope.row.sendNo }}</div>
                <div class="font-blue">
                  <span>{{ dict.sendStatus[scope.row.sendStatus] }}</span>
                  <span>-</span>
                  <span :class="scope.row.stopFlag == 1 ? 'font-red' : ''">{{ dict.stopFlag[scope.row.stopFlag] }}</span>
                  <template v-if="scope.row.thirdPushStatus != 0">
                    <span>-</span>
                    <span :class="scope.row.thirdPushStatus == 20 ? 'font-green' : 'font-red'">{{ dict.thirdPushStatus[scope.row.thirdPushStatus] }}</span>
                  </template>
                </div>
              </template>
            </el-table-column>
            <el-table-column width="130px" label="商品数量/重量" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.totalGoodsNum }}</span>
                <span>/</span>
                <span>{{ scope.row.totalGoodsWeight }}&nbsp;kg</span>
              </template>
            </el-table-column>
            <el-table-column width="120px" label="操作" align="right">
              <template slot-scope="scope">
                <el-button type="text" size="medium" class="table-btn" @click="doLinkDetail(scope.row)">查看详情</el-button>

                <template v-if="scope.row.sendStatus == 10 && warehouseInfo.warehouseType != 4">

                  <el-button type="text" size="medium" class="table-btn" @click="doDelete(scope.row)">删除单据</el-button>
               
                  <template v-if="scope.row.stopFlag == 0">
                    <template v-if="scope.row.thirdPushStatus > 0">
                      <el-button v-if="scope.row.thirdPushStatus == 20" type="text" size="medium" class="table-btn" @click="doCancelThird(scope.row)">撤销推送</el-button>
                      <el-button v-else type="text" size="medium" class="table-btn" @click="doPushThird(scope.row)">重新推送</el-button>
                    </template>

                    <template v-else>
                      <el-button type="text" size="medium" class="table-btn" @click="doPrint(scope.row)">打印面单</el-button>
                      <el-button type="text" size="medium" class="table-btn" @click="doConfirmDelivery(scope.row)">确认发货</el-button>
                    </template>
                  </template>

                </template>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="mar-t-28 mar-b-10">
          <strong>合计：{{ sendList.length }}&nbsp;笔</strong>
          <span>（已发货&nbsp;{{ sendList.filter(item => item.sendStatus == 30).length }}&nbsp;笔）</span>
        </div>
      </div>

    </div>

    <!-- 发货单发货dialog -->
    <el-dialog width="400px" v-el-drag-dialog title="确认发货" :visible.sync="sendDeliveryVisible" :center="true" append-to-body>
      <order-send-delivery :showFlag="sendDeliveryVisible" 
        :sendObj="selectedSendObj" 
        @callback="doCallbackSendDelivery">
      </order-send-delivery>
    </el-dialog>

    <!-- 发货单详情dialog -->
    <el-dialog width="1000px" v-el-drag-dialog title="发货单详情" :visible.sync="sendDetailVisible" append-to-body>
      <order-send-detail :showFlag="sendDetailVisible" 
        :sendId="selectedSendObj.sendId" 
        @callback="sendDetailVisible = false">
      </order-send-detail>
    </el-dialog>
    
    <!-- 打印面单dialog -->
    <el-dialog width="500px" v-el-drag-dialog title="打印面单" :visible.sync="printSendVisible" :center="true" append-to-body>
      <order-print-express :showFlag="printSendVisible" 
        :sendId="sendId" 
        :orderId="orderId" 
        @callback="printSendVisible = false">
      </order-print-express>
    </el-dialog>
  </div>
</template>

<script>
  import { getDictByGroupName } from '@/api/common/common'
  import {
    listCanDeliveryGoodsByApartOrderId,
    listSendByApartOrderId,
    createSend,
    doSendDelete,
    doSendPushThird,
    doSendCancelThird
  } from '@/api/order/projectSend'
  import { getApartOrder } from '@/api/goods/apartOrder'
  import { decryptReceiveInfo } from '@/api/goods/thirdOrder'
  import { getWarehouse } from '@/api/warehouse/warehouseInfo'
  import elDragDialog from '@/directive/el-dragDialog'
  import unlockIcon from '@/assets/images/unlock-icon.png'
  import lockIcon from '@/assets/images/lock-icon.png'
  import orderSendDelivery from '@/views/goods/order/components/order-send-delivery'
  import orderSendDetail from '@/views/goods/order/components/order-send-detail'
  import orderPrintExpress from '@/views/goods/order/components/order-print-express'

  export default {
    components: {
      orderSendDelivery, orderSendDetail, orderPrintExpress
    },
    directives: {
      elDragDialog
    },
    props: {
      showFlag: {
        type: Boolean,
        default() {
          return false
        }
      },
      // 子订单id
      apartOrderId: {
        type: String
      }
    },
    watch: {
      showFlag(val) {
        if (val) {
          this.init()
        }
      }
    },
    data() {
      return {
        // 子订单对象
        apartOrderObj: {
          projectOrder: {}
        },
        // 数据字典
        dict: {
          stopFlag: {},
          sendStatus: {},
          thirdPushStatus: {}
        },
        // 锁图标
        lockIcon,
        unlockIcon,
        // 锁标识
        isLock: false,
        loading: false,
        listLoading: false,
        sendListLoading: false,
        // 生成按钮控制
        generateBtnDisable: false,
        // 发货visible
        sendDeliveryVisible: false,
        // 发货单详情visible
        sendDetailVisible: false,
        // 订单商品列表
        orderGoodsList: [],
        // 发货单列表
        sendList: [],
        // 选中行
        selectedSendObj: {},
        // 父页面刷新flag
        refreshFlag: false,
        sendId: '',
        orderId: '',
        printSendVisible: false,
        // 仓库信息对象
        warehouseInfo: {
          warehouseType: ''
        }
      }
    },
    created() {
      // 获取数据字典
      getDictByGroupName('ApartOrderDTO').then(response => {
        Object.assign(this.dict, response.data)
      })
      // 获取数据字典
      getDictByGroupName('ProjectSendDTO').then(response => {
        Object.assign(this.dict, response.data)
      })
      if (this.getSystemRoleType() === '3') {
        getWarehouse(this.getWarehouseId()).then(response => {
          const data = response.data
          Object.assign(this.warehouseInfo, data)
        })
      }
      this.init()
    },
    methods: {
      // 初始化
      init() {
        this.loading = true
        const originData = this.$options.data()
        this.refreshFlag = originData.refreshFlag
        this.orderGoodsList = originData.orderGoodsList
        this.sendList = originData.sendList
        // 获取订单
        getApartOrder(this.apartOrderId).then(response => {
          this.loading = false
          if (response.isError) return
          this.apartOrderObj = response.data
          this.isLock = this.apartOrderObj.projectOrder.encryptReceiveFlag === 1
        })
        this.initGoodsList()
        this.initSendList()
      },
      // 获取可发货数商品信息
      initGoodsList() {
        this.listLoading = true
        listCanDeliveryGoodsByApartOrderId(this.apartOrderId).then(response => {
          this.listLoading = false
          if (response.isError) return
          this.orderGoodsList = response.data
          this.generateBtnDisable = this.orderGoodsList.filter(item => item.canSplitNum <= 0).length === this.orderGoodsList.length
        })
      },
      // 获取发货单
      initSendList() {
        this.sendListLoading = true
        listSendByApartOrderId(this.apartOrderId).then(response => {
          this.sendListLoading = false
          if (response.isError) return
          this.sendList = response.data
        })
      },
      // 解密事件
      doDecrypt(decryptReportType) {
        if (!this.isLock) {
          // 不再解密
          return
        }
        this.loading = true
        decryptReceiveInfo(this.apartOrderObj.projectOrder.externalOrderNo, this.apartOrderObj.projectOrder.externalPlatformType, decryptReportType).then(response => {
          this.loading = false
          if (response.isError) return
          this.isLock = false
          const data = response.data
          this.apartOrderObj.projectOrder.customerNickname = data.customerName
          this.apartOrderObj.projectOrder.customerPhone = data.customerPhone
          this.apartOrderObj.projectOrder.customerFullAddress = data.consigneeDetailAddress
        })
      },
      // 生成发货单
      doGenerateSend() {
        const list = this.orderGoodsList.filter(item => item.canSplitNum > 0)
        const fail_1_Count = list.filter(item => item.splitNum > item.canSplitNum).length
        if (fail_1_Count > 0) {
          this.$message({ type: 'warning', message: '发货数量不能大于可发数量，请确认' })
          return
        }
        const fail_2_Count = list.filter(item => item.splitNum === '' || item.splitNum < 0).length
        if (fail_2_Count > 0) {
          this.$message({ type: 'warning', message: '发货数量不能为空或小于0' })
          return
        }
        this.listLoading = true
        const form = {
          orderGoodsList: list
        }
        createSend(form).then(response => {
          if (response.isError) {
            this.listLoading = false
            return
          }
          this.$message({ type: 'success', message: '创建成功' })
          this.initGoodsList()
          this.initSendList()
        })
      },
      // 发货单删除事件
      doDelete(row) {
        this.$confirm('确定删除发货单？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.sendListLoading = true
          doSendDelete(row.sendId).then(response => {
            if (response.isError) {
              this.sendListLoading = false
              return
            }
            this.$message({ type: 'success', message: '删除成功' })
            this.initGoodsList()
            this.initSendList()
          })
        }).catch(() => {
        })
      },
      // 打印面单事件
      doPrint(row) {
        this.sendId = row.sendId
        this.orderId = row.orderId
        this.printSendVisible = true
        // alert('暂未实现' + row.sendId)
      },
      // 推送事件
      doPushThird(row) {
        this.listLoading = true
        doSendPushThird(row.sendId).then(response => {
          if (response.isError) {
            this.listLoading = false
            return
          }
          this.$message({ type: 'success', message: '推送成功' })
          this.initList()
        })
      },
      // 撤销事件
      doCancelThird(row) {
        this.listLoading = true
        doSendCancelThird(row.sendId).then(response => {
          if (response.isError) {
            this.listLoading = false
            return
          }
          this.$message({ type: 'success', message: '撤销成功' })
          this.initList()
        })
      },
      // 确认发货事件
      doConfirmDelivery(row) {
        this.selectedSendObj = row
        this.sendDeliveryVisible = true
      },
      // 发货回调事件
      doCallbackSendDelivery(callbackFlag) {
        if (callbackFlag) {
          this.refreshFlag = true
          this.initSendList()
        }
        this.sendDeliveryVisible = false
      },
      // 查看详情事件
      doLinkDetail(row) {
        this.selectedSendObj = row
        this.sendDetailVisible = true
      },
      // 关闭事件
      doClose() {
        this.$emit('callback', this.refreshFlag)
      }
    }
  }
</script>

<style scoped>
  .el-divider--vertical {
    height: auto;
  }
</style>